package com.zys.el.time.advice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zys.el.time.advice.entity.CommentAdvice;
import com.zys.el.time.advice.mapper.CommentAdviceMapper;
import com.zys.el.time.advice.service.CommentAdviceService;
import com.zys.el.time.advice.vo.CommentAdviceVo;
import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.dto.ScrollPage;
import com.zys.el.time.service.impl.UserService;
import com.zys.el.time.service.redis.CacheClient;
import com.zys.el.time.vojo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CommentAdviceServiceImpl extends ServiceImpl<CommentAdviceMapper, CommentAdvice>
        implements CommentAdviceService {
    @Resource
    private UserService userService;
    @Resource
    private CacheClient cacheClient;


    @Override
    public CommentAdviceVo getCommentAdviceVoById(Long adviceId){
        String adviceKey = RedisConstants.ADVICE_KEY + adviceId;
        CommentAdvice commentAdvice = cacheClient.queryWithoutLock(adviceKey, adviceId, CommentAdvice.class, this::getById);
        UserVo userVo = userService.queryUser(commentAdvice.getFromUserId());
        CommentAdviceVo commentAdviceVo = new CommentAdviceVo();
        BeanUtils.copyProperties(commentAdvice, commentAdviceVo);
        commentAdviceVo.setMsger(userVo);
        return commentAdviceVo;
    }

    @Override
    public ScrollPage<CommentAdviceVo> getPage(Long userId, Long max, int offset, int size) {

        String advicePageKey = RedisConstants.PAGE_USER_INBOX_COMMENT_KEY + userId;

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", userId);
        return cacheClient.queryScrollPage(advicePageKey, map, max, offset, size,
                this::getCommentAdviceVoById, this::queryCommentAdvicePage);

    }

    @Override
    public void clear(Long userId) {
        QueryWrapper<CommentAdvice> qw = new QueryWrapper<>();
        qw.lambda().eq(CommentAdvice::getToUserId, userId);
        this.remove(qw);
    }

    @Override
    public void alreadyRead(Long userId) {
        this.update().eq("user_id", userId).setSql("status = 2").update();
    }


    private List<CommentAdvice> queryCommentAdvicePage(Map<String, Object> map){
        Long id = (Long) map.get("id");
        Long startIdx = (Long) map.get("startIdx");
        int size = (int) map.get("size");
        return this.baseMapper.getPageByUserId(id, startIdx, size);
    }

}




